<template>
  <div class="main" v-loading="detailLoading">
    <el-collapse v-model="activeNames">
      <el-collapse-item title="基础信息" name="base">
        <el-form ref="form" size="mini" :model="form" :disabled="openType=='view'" label-width="90px" :rules="rules">
          <el-row :gutter="24">
            <responseBox>
              <el-form-item label="产品名称" prop="materialId" v-if="openType=='add'">
                <el-select v-model="form.materialId" filterable placeholder="产品名称" @change="productionLineChange" style="width: 100%">
                  <el-option v-for="item in productionLineList" :key="item.id" :label="item.materialName" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="产品名称" prop="materialName" v-if="openType!='add'">
                <el-select v-model="form.materialName" disabled filterable placeholder="产品名称" @change="productionLineChange" style="width: 100%">
                  <el-option v-for="item in productionLineList" :key="item.id" :label="item.materialName" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </responseBox>
            <responseBox>
              <el-form-item label="产品编号" prop="materialNo">
                <el-input v-model="form.materialNo" placeholder="产品编号" disabled></el-input>
              </el-form-item>
            </responseBox>
            <responseBox>
              <el-form-item label="配方号" prop="formulaNo">
                <el-input v-model="form.formulaNo" placeholder="配方号" :disabled="openType=='edit'"  clearable></el-input>
              </el-form-item>
            </responseBox>
          </el-row>
        </el-form>
      </el-collapse-item>
      <el-collapse-item title="配方" name="formula">
        <el-form ref="form1" size="mini" :model="form1" label-width="90px" v-if="openType!='view'">
          <el-row :gutter="24">
            <!-- <el-col :span="7">
              <el-form-item label="零件类型" prop="bomMaterialType">
                <el-cascader style="width: 100%" v-model="form1.bomMaterialType" :options="materialTypes" :props="materialTypeProps" @change="materialTypeChange"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="零件组" prop="materialGroupNo">
                <el-select v-model="form1.materialGroupNo" clearable filterable placeholder="请选择零件组" @change="materialGroupChange" style="width: 100%">
                  <el-option v-for="item in materialGroupList" :key="item.id" :label="item.materialGroupName" :value="item.materialGroupNo"></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="8">
              <el-form-item label="物料" prop="bomNo">
                <!-- <el-select v-model="form1.bomNo" remote :remote-method="remoteMethods" :loading="searchloading" clearable filterable placeholder="请选择零件" style="width: 100%"> -->
                <el-select v-model="form1.bomNo" :loading="searchloading" clearable filterable placeholder="请选择物料" style="width: 100%">
                  <el-option v-for="item in bomNoList" :key="item.id" :label="item.materialName" :value="item.materialNo"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="addMaterial"></el-button>
            </el-col>
          </el-row>
        </el-form>
        <avue-crud ref="infoCrud" class="noMenuHtml" :option="infoOption" :data="childPrdBomList">
          <template slot="stationNo" slot-scope="{row}">
            <el-select size="mini" v-if="row.isEdit" v-model="row.stationNo" clearable filterable placeholder="请选择工位" style="width: 100%">
              <el-option v-for="item in stationNoList" :key="item.id" :label="item.stationCode" :value="item.stationCode"></el-option>
            </el-select>
<!--            <el-input v-if="row.isEdit" v-model="row.stationNo" size="mini" placeholder="工位"></el-input>-->
            <span v-else>{{row.stationNo}}</span>
          </template>
          <template slot="buckleType" slot-scope="{row}">
            <el-select size="mini" v-if="row.isEdit" v-model="row.buckleType" clearable filterable placeholder="扣料配置" style="width: 100%">
              <el-option v-for="item in buckleTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <span v-else>{{getName(row.buckleType)}}</span>
          </template>
          <template slot="quota" slot-scope="{row}">
            <el-input size="mini" v-if="row.isEdit" v-model="row.quota" maxlength="3" placeholder="单件用量" v-Perint></el-input>
            <span v-else>{{row.quota}}</span>
          </template>
          <template slot="errorValue" slot-scope="{row}">
            <el-input size="mini" v-if="row.isEdit" v-model="row.errorValue" maxlength="2" placeholder="错误值配置" v-zero></el-input>
            <span v-else>{{row.quota}}</span>
          </template>
          <template slot="menu" slot-scope="{row}">
            <el-tooltip content="复制" style="height:auto" effect="dark" class="rightbtn" placement="bottom">
              <div class="top-bar__item">
                <el-button type="text" size="small" icon="el-icon-document-copy" @click.stop="copyFn(row)"></el-button>
              </div>
            </el-tooltip>
            <el-tooltip content="删除" style="height:auto" effect="dark" class="rightbtn" placement="bottom">
              <div class="top-bar__item">
                <el-button type="text" size="small" icon="el-icon-delete" @click.stop="rowDel(row)"></el-button>
              </div>
            </el-tooltip>
          </template>
        </avue-crud>
      </el-collapse-item>
    </el-collapse>

    <div class="center mt">
      <el-button icon="el-icon-circle-close" :loading="saveLoading" size="mini" @click="$emit('close')">取 消</el-button>
      <el-button icon="el-icon-circle-plus-outline" :loading="saveLoading" v-show="openType=='add'" size="mini" @click="saveFn('goon')">保存并继续</el-button>
      <el-button icon="el-icon-circle-plus-outline" :loading="saveLoading" type="primary" v-show="openType!='view'" size="mini" @click="saveFn('save')">保 存</el-button>
    </div>
  </div>
</template>

<script>
import responseBox from '@/components/base-small/response-box.vue'
import * as product from '@/api/project/productData/product'
import { getMaterialgroupList } from '@/api/project/productData/baseData';
import { findByProductionLine, productBomList } from './ajax.js'
import {bomproductList, getMaterialListForFormula, produceStationList} from "@/api/project/productData/product";
export default {
  name: 'MainCom',
  props: ['detailId','openType'],
  components: {
    responseBox
  },
  data () {
    return {
      channelNoList: [],
      productionLineList: [],
      searchloading: false,
      ajaxed: false,
      activeNames: ['base', 'formula'],
      detailLoading: false,
      saveLoading: false,
      form: {
        materialNo: '',
        erpAssemblyId: '',
        productionLineCode: '',
        formulaNo: '',
      },
      materialNoList: [],
      ERPmaterialNoList: [],
      rules: {
        // productionLineCode: [
        //   { required: true, message: '请选择生产线', trigger: 'change',}
        // ],
        // erpAssemblyId: [
        //   { required: true, message: '请选择ERP总成号', trigger: 'change',}
        // ],
        materialId: [
          { required: true, message: '请选择产品名称', trigger: 'change',}
        ]
      },

      form1: {
        bomMaterialType: [],
        materialGroupNo: '',
        bomNo: '',
      },
      materialTypeProps: {
        label: 'dictValue',
        value: 'dictKey',
      },
      buckleTypeList:[
        {
          label:'工位',value:1
        },
        {
          label:'站位',value:2
        },
      ],
      materialTypes: [],
      materialGroupList: [],
      bomNoList: [],
      stationNoList: [],
      childPrdBomList: [],
      infoOption: {
        tip: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        index: true,
        border:true,
        menuWidth: 80,
        viewBtn:false,
        menu: true,
        column: [
          {
            label: '物料编码',
            prop: 'materialNo',
            minWidth: 130,
            overHidden: true,
          },
          {
            label: '物料名称',
            prop: 'materialName',
            minWidth: 130,
            overHidden: true,
          },
          {
            label: '工位',
            prop: 'stationNo',
            minWidth: 130,
            // overHidden: true,
            slot: true,
            renderHeader: (h, { column }) => {
              return h('span', [
                h('span', {style: {color: 'red',paddingRight: '4px'}},'*'),
                h('span', column.label),
              ]);
            },
          },
          {
            label: '单件用量',
            prop: 'quota',
            minWidth: 130,
            overHidden: true,
            slot: true,
            renderHeader: (h, { column }) => {
              return h('span', [
                h('span', {style: {color: 'red',paddingRight: '4px'}},'*'),
                h('span', column.label),
              ]);
            },
          },
          {
            label: '扣料配置',
            prop: 'buckleType',
            slot:true,
            minWidth: 130,
            overHidden: true,
          },
          {
            label: '错误值配置',
            prop: 'errorValue',
            slot:true,
            minWidth: 130,
            overHidden: true,
          },
          {
            label: '计量单位',
            prop: 'unit',
            minWidth: 90,
            overHidden: true,
          },
        ]
      },
    }
  },
  created () {
    // getBusinessList('channel_no').then(res => {
    //   this.channelNoList = res.data.data
    // })
    produceStationList().then(res=>{
      this.stationNoList = res.data.data
    })

    getMaterialListForFormula().then(res=>{
      this.bomNoList = res.data.data;
    })
    bomproductList().then(res => {
      this.productionLineList = res.data.data
    })
    if (this.openType == 'view') {
      this.infoOption.menu = false
    } else {
      this.infoOption.menu = true
    }
    // product.getMaterialTypeTree({ code: 'materials', dictKey: 'M,P' }).then((res) => {
    //   this.materialTypes = res.data.data
    // });
    // product.masterProducts().then(res => {
    //   this.ERPmaterialNoList = res.data.data.map(item => {
    //     item.label = item.materialName + '(' + item.materialNo + ')'
    //     item.value = item.materialNo
    //     return item
    //   })
    // })
    // product.bomproductList().then(res => {
    //   this.materialNoList = res.data.data.map(item => {
    //     item.label = item.materialName + '(' + item.materialNo + ')'
    //     item.value = item.materialNo
    //     return item
    //   })
    //   this.ajaxed = true
    // })
    if (this.openType != 'add') {
      this.detailLoading = true
      product.bomDetail(this.detailId).then((res) => {
        let data = res.data.data;
        this.form = data;
        this.childPrdBomList = data.childPrdBomList.map(item => {
          item.materialTypes = [item.productFlag, item.productType]
          if (this.openType != 'view') {
            this.$set(item, 'isEdit', true)
          }
          return item
        })
        // if (this.openType == 'copy') {
        //   this.$set(this.form, 'materialNo', '');
        //   // this.$set(this.form, 'productionLineCode', '');
        //   this.$set(this.form, 'formulaNo', '');
        //   this.$nextTick(() => {
        //     this.$refs.form.clearValidate()
        //   })
        // }
        // if (this.openType == 'edit' || this.openType == 'view') {
        //   let timer = setInterval(() => {
        //     if (this.ajaxed) {
        //       clearInterval(timer)
        //       timer = null
        //       if (this.materialNoList.findIndex((res) => res.value == this.form.materialNo) == -1) {
        //         this.materialNoList.unshift({
        //           label: this.form.materialName + '(' + this.form.materialNo + ')',
        //           value: this.form.materialNo,
        //         });
        //       }
        //     }
        //   }, 100)
        // }
        this.detailLoading = false
      })
    }
  },
  methods: {
    erpAssemblyIdChange (val) {
      productBomList(val).then(res => {
        this.childPrdBomList = res.data.data.map(item => {
          delete item.children
          item.isEdit = true
          return item
        })
        this.bomNoList = res.data.data.map(item => {
          item.label = item.materialName + '(' + item.materialNo + ')'
          item.value = item.materialNo
          return item
        })
      })
    },
    productionLineChange (val) {
      this.form.materialNo = "";
      this.form.materialName = "";
      if(val){
       let material = this.productionLineList.find(item=>item.id == val);
       if(material && material.id){
         this.form.materialNo = material.materialNo
         this.form.materialName = material.materialName
       }
      }
      // this.form.erpAssemblyId = ''
      // this.form.materialNo = ''
      // this.childPrdBomList = []
      // findByProductionLine({productionLine: val}).then(res => {
      //   this.ERPmaterialNoList = res.data.data.map(item => {
      //     item.label = item.materialName + '(' + item.materialNo + ')'
      //     item.value = item.materialNo
      //     return item
      //   })
      //   this.materialNoList = this.ERPmaterialNoList
      // })
      // this.getStationNoList(val)
    },
    remoteMethods(query) {
      if (query !== '') {
        this.searchloading = true;
        let params = {
          materialName: query
        }
        if (this.form1.bomMaterialType[1]) {
          params.materialType = this.form1.bomMaterialType[1]
        }
        if (this.form1.materialGroupNo) {
          params.materialGroupNo = this.form1.materialGroupNo
        }
        product.materialList(params).then(res => {
          this.bomNoList = res.data.data.map((item) => {
            return {
              label: item.materialName + '(' + item.materialNo + ')',
              value: item.materialNo,
            }
          })
          this.searchloading = false
        }).catch(() => {
          this.bomNoList = []
          this.searchloading = false
        })
      } else {
        this.bomNoList = [];
        this.searchloading = false
      }
    },
    materialTypeChange (val) {
      this.form1.materialGroupNo = ''
      this.form1.bomNo = ''
      if (val) {
        getMaterialgroupList({ materialType: val.join(',') }).then((res) => {
          this.materialGroupList = res.data.data
        });
        product.materialList({ materialType: val[1] }).then((res) => {
          this.bomNoList = res.data.data.map((item) => {
            item.label = item.materialName + '(' + item.materialNo + ')'
            item.value = item.materialNo
            return item
          });
        });
      } else {
        this.materialGroupList = []
        this.bomNoList = []
      }
    },
    materialGroupChange (val) {
      this.form1.bomNo = ''
      if (val) {
        product.materialList({ materialType: this.form1.bomMaterialType[1], materialGroupNo: val }).then((res) => {
          this.bomNoList = res.data.data.map((item) => {
            item.label = item.materialName + '(' + item.materialNo + ')'
            item.value = item.materialNo
            return item
          })
        })
      } else {
        product.materialList({ materialType: val[1] }).then((res) => {
          this.bomNoList = res.data.data.map((item) => {
            item.label = item.materialName + '(' + item.materialNo + ')'
            item.value = item.materialNo
            return item
          })
        })
      }
    },
    materialChange(val) {
      let item = this.materialNoList.find(row => row.value == val)
      // if (this.form.productionLineCode != item.productionLineCode) {
      //   this.childPrdBomList.forEach(item => {
      //     this.$set(item, 'stationNo', '')
      //   })
      // }
      // this.form.productionLineCode = item.productionLineCode
      this.form.formulaNo = item.formulaNo
    },
    getStationNoList (productionLine) {
      product.listByProductionLine({productionLine: productionLine}).then(res => {
        this.stationNoList = res.data.data
      })
    },
    addMaterial() {
      if (!this.form1.bomNo) {
        this.$message.error('请选择要添加的物料');
        return;
      } else {
        if(!this.form.materialNo) {
          this.$message.error('请先选择产品名称');
          return;
        }
        // if (this.childPrdBomList.length > 0) {
        //   let isHave = false;
        //   isHave = this.childPrdBomList.some((item) => item.materialNo == this.form1.bomNo);
        //   if (isHave) {
        //     this.$message.error('零件已添加，不可重复添加');
        //     return;
        //   }
        // }
        this.bomNoList.forEach((item) => {
          if (this.form1.bomNo == item.materialNo) {
            if (this.form.materialNo && this.form.materialNo == this.form1.bomNo) {
              this.$message.error('添加的零件不可以与产品相同');
            } else {
              let target = {...item}
              this.$set(target, 'isEdit', true)
              this.$set(target, 'stationNo', '')
              this.$set(target, 'quota', '')
              // target.materialTypes = [target.materialFlag,target.materialType]
              delete target.id
              this.childPrdBomList.push({...target})
              console.log(this.childPrdBomList)
            }
            return false
          } else {
            return true
          }
        });
      }
    },
    copyFn (row) {
      let item = {...row}
      this.$set(item, 'isEdit', true)
      this.$set(item, 'stationNo', '')
      this.$set(item, 'quota', '')
      this.$set(item, 'buckleType', '')
      this.$set(item, 'errorValue', '')
      delete item.id
      this.childPrdBomList.splice(row.$index+1, 0, item);
    },
    getName(code){
      let type =  this.buckleTypeList.find(item=>item.value == code);
      if(type && type.value){
        return type.label;
      }else{
        return "";
      }
    },
    rowDel (row) {
      this.childPrdBomList.splice(row.$index, 1);
    },
    saveFn (type) {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.childPrdBomList.length == 0) {
            this.$message.error(' 【配方】不能为空')
            return
          }
          let pass = this.childPrdBomList.every((item, index) => {
            if (!item.stationNo) {
              this.$message.error(`【配方】第${index + 1}行 请输入工位`);
              return false;
            }
            if (!item.quota) {
              this.$message.error(`【配方】第${index + 1}行 请输入单件用量`);
              return false;
            }
            return true
          })
          if (!pass) {
            return
          }
          for (let i=0;  i<this.childPrdBomList.length; i++) {
            if (this.childPrdBomList.some(item => (item.materialNo + item.stationNo) == (this.childPrdBomList[i].materialNo + this.childPrdBomList[i].stationNo) && item.$index != this.childPrdBomList[i].$index)) {
              this.$message.error('零件号+工位“'+this.childPrdBomList[i].materialNo + '+'+ this.childPrdBomList[i].stationNo+'”已存在')
              // this.$message.warning(this.childPrdBomList[i].materialNo+ '+' + this.childPrdBomList[i].stationNo+'已存在')
              return
            }
          }
          if (this.openType == 'add' || this.openType == 'copy') {
            let children = this.childPrdBomList.map((item) => {
              if (item.id) {
                delete item.id
              }
              return item
            })
            this.form.dataSource = '1'
            this.form.id = ''
            let content = { ...this.form, childPrdBomList: children }
            this.saveLoading = true
            product.bomAdd(content).then(res => {
              this.$message.success(res.data.msg)
              if (type == 'goon') {
                this.clearForm()
              }
              this.saveLoading = false
              this.$emit('reload', type)
            }).catch(() => {
              this.saveLoading = false
            })
          }
          if (this.openType == 'edit') {
            let content = { ...this.form, childPrdBomList: this.childPrdBomList };
            product.bomUpdate(content).then(res => {
              this.$message.success(res.data.msg)
              this.$emit('reload')
            })
          }
        }
      })
    },
    clearForm () {
      this.form.materialNo = ''
      this.form.materialId = ''
      this.form.materialName= ""
      this.form.erpAssemblyId = ''
      this.form.productionLineCode = ''
      this.form.formulaNo = ''
      this.form1.bomMaterialType = ''
      this.form1.materialGroupNo = ''
      this.form1.bomNo = ''
      this.childPrdBomList = []
      this.materialGroupList = []
      this.bomNoList = []
      product.bomproductList().then(res => {
        this.materialNoList = res.data.data.map(item => {
          item.label = item.materialName + '(' + item.materialNo + ')'
          item.value = item.materialNo
          return item
        })
      })
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
  }
}
</script>

<style scoped lang="scss">
.main /deep/ .el-collapse-item__header {
  color: #409eff;
  font-size: 16px;
  height: 30px;
  line-height: 30px;
  font-weight: 700;
}
</style>
